package com.jihox.abookpro.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;

import com.jihox.abookpro.MyApplication;

public class MaskView extends View {
	
	private Paint mLinePaint;
	private Paint mAreaPaint;
	private Rect mCenterRect = null;
	private int widthScreen;
	private int heightScreen;
	private int cx =0;
	private int cy = 0;
	private int radius =0;
	
	public MaskView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initPaint();
		
		WindowManager wm = (WindowManager)MyApplication.getInstance().getSystemService(Context.WINDOW_SERVICE);
		widthScreen = wm.getDefaultDisplay().getWidth();
		heightScreen = wm.getDefaultDisplay().getHeight();
	}

	private void initPaint(){
		//绘制中间透明区域矩形边界的Paint
		mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mLinePaint.setColor(Color.WHITE);
		mLinePaint.setStyle(Style.STROKE);
		mLinePaint.setStrokeWidth(5f);
		mLinePaint.setAlpha(30);

		//绘制四周阴影区域
		mAreaPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mAreaPaint.setColor(Color.BLACK);
		mAreaPaint.setStyle(Style.FILL);
		mAreaPaint.setAlpha(180);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (mCenterRect !=null){
			canvas.drawRect(0, 0, widthScreen, mCenterRect.top, mAreaPaint);
			canvas.drawRect(0, mCenterRect.bottom + 1, widthScreen, heightScreen, mAreaPaint);
			canvas.drawRect(0, mCenterRect.top, mCenterRect.left - 1, mCenterRect.bottom  + 1, mAreaPaint);
			canvas.drawRect(mCenterRect.right + 1, mCenterRect.top, widthScreen, mCenterRect.bottom + 1, mAreaPaint);
			//绘制目标透明区域
			canvas.drawRect(mCenterRect, mLinePaint);
		}else if (radius!=0f){
			canvas.drawRect(0, 0, widthScreen, cy-radius, mAreaPaint);
			canvas.drawRect(0, cy + radius, widthScreen, heightScreen, mAreaPaint);
			canvas.drawRect(0, cy-radius, cx - radius, cy + radius, mAreaPaint);
			canvas.drawRect(cx+radius, cy-radius, widthScreen, cy + radius, mAreaPaint);
			float strokeWidth = radius*2;
			//设置画笔style为画实心的
			mAreaPaint.setStyle(Style.STROKE);
			mAreaPaint.setStrokeWidth(strokeWidth);
			canvas.clipRect(new Rect(cx - radius,cy-radius,cx + radius,cy+radius));
			canvas.drawCircle(cx, cy, radius + strokeWidth/2, mAreaPaint);
		}else{
			canvas.drawRect(0, 0, widthScreen, heightScreen, mAreaPaint);
		}
		
		super.onDraw(canvas);
	}   

	public void setCenterRect(Rect r){
		this.mCenterRect = r;
		postInvalidate();
	}
	
	public void setCircle(int x,int y,int radius){
		this.cx = x;
		this.cy = y;
		this.radius = radius;
		postInvalidate();
	}
}
